import { Button, Form, Input, message, Drawer, Cascader, Select, Space } from "antd"
import { useImperativeHandle, useState } from 'react';
import Upload from '../../components/upload'
import * as apis from '../../lib/api'
import http from '../../lib/http'
import FabricParam from '../../components/fabric_param'
import * as THREE from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'

const Index = (props) => {
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [form] = Form.useForm()
    const [loading, setLoading] = useState(false)
    const [fieldsValue, asetFieldsValue] = useState({})

    useImperativeHandle(props.funcs, () => ({
        setIsModalOpen,
        resetFields: form.resetFields,
        setFieldsValue: (vals) => {
            asetFieldsValue(vals)
            form.setFieldsValue(vals)
        }
    }));

    const loadAndCheck = (path) => {
        const meshs = new Map()
        const marr = []
        let loader = new OBJLoader()
        let modelType = ""
        if(path.indexOf(".obj") !== -1){
            modelType = "obj"
        }else{
            modelType = "glb"
            loader = new GLTFLoader()
        }
        return new Promise((resolve, reject) => {
            loader.load(path, async (objects) => {
                if (modelType === "glb"){
                    objects = objects.scene
                }
                for (let i = 0; i < objects.children.length; i++) {
                    let child = objects.children[i]
                    if (child.isMesh) {
                        meshs.set(child.name,1)
                        marr.push(child.name)
                    }
                }
                // console.log(marr,meshs)
                if(meshs.size !== marr.length){
                    reject(`模型内有重复版片名称，请重新上传`)
                    return
                }
                resolve(null)
            }, xhr => {
                // let p = (xhr.loaded / xhr.total) * 100;
                // onProgress(p.toFixed(2))
            }, error => {
                reject(error)
            })
        })
    }

    const submit = async () => {
        try {
            const data = await form.validateFields()
            const post = {
                cover: data.cover[0].url,
                path: data.path[0].url,
                name: data.name, 
                design_file_path: data.design_file_path[0].url,
                tags: data?.tags?.join(),
                category_id: data.category_id[0] ? data.category_id[0]:0, 
                second_category_id: data.category_id[1] ? data.category_id[1]:0, 
                three_category_id: data.category_id[2] ? data.category_id[2]:0
            }

            //加载模型检测重复mesh
            setLoading(true)
            await loadAndCheck(process.env.REACT_APP_OSS_URL+post.path)

            if(!fieldsValue.id){
                try {
                    await http.post(apis.MODEL_CREATE, post)
                    setIsModalOpen(false)
                    message.success("新建成功")
                    props.onRefresh && props.onRefresh(1)
                } catch (error) {
                    
                }
                setLoading(false)
            }else{
                try {
                    post.id = fieldsValue.id
                    await http.post(apis.MODEL_UPDATE, post)
                    setIsModalOpen(false)
                    message.success("更新成功")
                    props.onRefresh && props.onRefresh()
                } catch (error) {
                    
                }
                setLoading(false)
            }
        } catch (error) {
            console.log(error)
            message.error(error)
            setLoading(false)
        }
    }


    return (
        <>
            <Drawer 
                forceRender
                open={isModalOpen} 
                onClose={() => {
                    if(loading) return 
                    setIsModalOpen(false)
                }}
                width="100vw"
                title={!fieldsValue.id ? '新增模型':'更新模型'}
                footer={null
                    // <div style={{textAlign: "right"}}>
                    //     <Space>
                    //         <Button loading={loading} onClick={() => setIsModalOpen(false)}>取消</Button>
                    //         <Button loading={loading} type="primary" onClick={submit}>确定</Button>
                    //     </Space>
                    // </div>
                }
                extra={
                    <Space>
                        <Button loading={loading} type="primary" onClick={submit}>保存</Button>
                    </Space>
                }
            >
                <Form form={form} autoComplete="off" labelAlign="right" labelCol={{span: 4}}>
                    <Form.Item name="name" label="名称">
                        <Input placeholder="请输入" />
                    </Form.Item>
                    <Form.Item name="tags" label="标签">
                        <Select
                            mode="tags"
                            placeholder="输入标签"
                        />
                    </Form.Item>
                    <Form.Item name="category_id" label="所属分类" rules={[{required: true, message: "请选择"}]}>
                        <Cascader style={{width: "100%"}} allowClear options={props?.category} placeholder="请选择" />
                    </Form.Item>
                    <Form.Item name="cover" label="封面" rules={[{required: true, message: "请上传"}]}>
                        <Upload />
                    </Form.Item>
                    <Form.Item name="path" label="模型文件" rules={[{required: true, message: "请上传"}]}>
                        <Upload size={1024*50} accept=".obj,.glb" />
                    </Form.Item>
                    <Form.Item name="design_file_path" label="设计文件" rules={[{required: true, message: "请上传"}]}>
                        <Upload size={1024*200} accept="*" />
                    </Form.Item>
                </Form>
            </Drawer>
        </>
    )
}

export default Index